// Finance.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "Finance.h"

#include "CDataFile.h"
#include "financedef.h"
#include "CryptString.h"
#include "cshellfileop.h"

// for ext source
#include "MPIDocTemplate.h"
#include "MPIChildFrame.h"

#include "MainFrm.h"
#include "FinanceDoc.h"
#include "FinanceView.h"
#include "CountView.h"
#include "SearchView.h"
#include "TreeCountView.h"
#include "BankView.h"

#include "DlgLogin.h"

#include "BtnST.h"	// Added by ClassView
#include "HyperLink.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif


// 
// default pwd(IDS_DEFAULTPWD) is defined in "financedef.h"
//------------------------------------------------------------
void	GetAPDefaultPwd( LPTSTR pchEncrypted )
{
	// Init the crypto class
	CCryptString	oCrypt;

	if( NULL == pchEncrypted ) 
		return	;
	
	// encrpyt new
	oCrypt.EncryptString( IDS_DEFAULTPWD, pchEncrypted, IDS_PWDKEY );
}


// !!!
// Invoke ".chm" in VC
// <1> include "htmlhelp.h" in "StdAfx.h"
// <2> Set Additional include dir for "htmlhelp.h"
// <3> inport "htmlhelp.lib" in Link input
// <4> Set Additional library path in Link 
// <5> Add below code to invoke ".chm"
//------------------------------------------------------------
void	OnExecHelper() 
{
	CString appPath;
	
	GetModuleFileName( NULL, appPath.GetBuffer(MAX_PATH), MAX_PATH );
	
	appPath.ReleaseBuffer();
	INT n = appPath.ReverseFind('\\');
	
	CString helpFile;
	helpFile = appPath.Left(n);
	TCHAR c = helpFile.GetAt(n - 1);
	if(c == '\\')
		helpFile += "Finance.chm";
	else
		helpFile += "\\Finance.chm";
	
	HtmlHelp(NULL, (LPCSTR)helpFile, HH_DISPLAY_TOPIC, 0);
}



/////////////////////////////////////////////////////////////////////////////
// CFinanceApp

BEGIN_MESSAGE_MAP(CFinanceApp, CWinApp)
	//{{AFX_MSG_MAP(CFinanceApp)
	ON_COMMAND(ID_APP_ABOUT, OnAppAbout)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
	// Standard file based document commands
	ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew)
	ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen)
	// Standard print setup command
	ON_COMMAND(ID_FILE_PRINT_SETUP, CWinApp::OnFilePrintSetup)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CFinanceApp construction

CFinanceApp::CFinanceApp()
{
	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CFinanceApp object

CFinanceApp theApp;

/////////////////////////////////////////////////////////////////////////////
// CFinanceApp initialization

BOOL CFinanceApp::InitInstance()
{

	// the AP can run one instance at the same time only .
    HANDLE m_hMutex = CreateMutex( NULL, TRUE, m_pszAppName ); 
    if( GetLastError() == ERROR_ALREADY_EXISTS )
	{ 
		::MessageBox( NULL, "An finance application has been run before!", "Warning", MB_ICONWARNING );
		return FALSE; 
	}

	// <> Init registry key
	InitRegistry();

	// <> check popup login dlg or not
	BYTE	btEnablePop = 1;	// default
	HKEY	hRegKey = NULL;
	
	// <> get password form Register
	if( RegOpenKeyEx( HKEY_CURRENT_USER, IDS_REGSRBKEY, 0, KEY_QUERY_VALUE, &hRegKey ) == ERROR_SUCCESS ) 
	{		
		DWORD	dwLength = sizeof(btEnablePop);
		DWORD	dwType = REG_BINARY;
		
		if( RegQueryValueEx( hRegKey, _T("Popup"), NULL, &dwType, (BYTE*)&btEnablePop, &dwLength ) != ERROR_SUCCESS )
			btEnablePop = 1;	// default
		
		::RegCloseKey( hRegKey );	
	}
	
	if( 1 == btEnablePop )
	{
		CDlgLogin	dlg;
		
		if( dlg.DoModal() == IDOK )
		{
			;
		}

		if( !dlg.IsCheckedOK() ) 
		{
			return FALSE;
		}
	}
	
	InitCommonControls();
	
	CWinApp::InitInstance();
	
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));
	
	// ------------------------------------------------------------------------------------------------
	// <> Init config file
	InitConfigFile();
	
	// Initialize COM and ADO
	AfxOleInit();
	
	try
	{  
#ifdef _USING_UDL_
		m_pConnection.CreateInstance(__uuidof(Connection));   
		m_pConnection->ConnectionString ="File Name=Finance.udl"; 
		m_pConnection->Open("","","",NULL); 
#else
		HRESULT hr = m_pConnection.CreateInstance("ADODB.Connection");
		if( SUCCEEDED(hr) )
		{
			hr = m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\Mmoney.mdb","","",adModeUnknown);
		}
#endif
	}
	catch(_com_error e)
	{
		CString strComError;
		
		strComError.Format( "Error No: %08lx\nError info: %s\nError source: %s\nError Description: %s",
			e.Error(),                  // Error No
			e.ErrorMessage(),           // Error info
			(LPCSTR) e.Source(),        // Error source
			(LPCSTR) e.Description() );  // Error Description      
		
		::MessageBox( NULL, strComError, "Error", MB_ICONEXCLAMATION );
	}
	// ---------------------------------------------------------------------------------------------------
	
	CMPIDocTemplate* pDocTemplate;
	pDocTemplate = new CMPIDocTemplate(
		IDR_MAINFRAME,
		RUNTIME_CLASS(CFinanceDoc),
		RUNTIME_CLASS(CMPIChildFrame));
	AddDocTemplate(pDocTemplate);
	
	CMainFrame* pMainFrame = new CMainFrame;
	if (!pMainFrame->LoadFrame(IDR_MAINFRAME))
		return FALSE;
	
	m_pMainWnd = pMainFrame;
	
	CDocument* pDocument = pDocTemplate->CreateNewDocument();
	
	// define layout of the MPI frames
	
	BEGIN_MPI_FRAME(pDocTemplate, IDR_FIRST)
		MPI_VSPLIT(0)	
		MPI_VIEW(CTreeCountView)
		MPI_TABS(IDR_TABS)
		MPI_VIEW_EX(CFinanceView, 1)
		MPI_VIEW_EX(CCountView, 2)
		MPI_VIEW_EX(CSearchView, 3)
		MPI_VIEW_EX(CBankView, 4)
		END_MPI_FRAME
		
	pMainFrame->MDIActivate(pDocTemplate->GetChildFrame(0));
	pMainFrame->ShowWindow(m_nCmdShow);
	pMainFrame->UpdateWindow();
	
	return TRUE;
}


/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	virtual BOOL OnInitDialog();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()

private:
	CHyperLink m_HomePageLink;
	CHyperLink m_EMailLink;
	CButtonST m_btnOk;
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	DDX_Control(pDX, IDOK, m_btnOk);
	DDX_Control(pDX, IDC_EMAILLINK, m_EMailLink);
	DDX_Control(pDX, IDC_HOMEPAGELINK, m_HomePageLink);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

// App command to run the dialog
void CFinanceApp::OnAppAbout()
{
	CAboutDlg aboutDlg;
	aboutDlg.DoModal();
}

/////////////////////////////////////////////////////////////////////////////
// CFinanceApp message handlers


//
// default value when new ini file
// [date range]
// range type = all
// begin date = 0
// end date = time_t of (current year/12/31)
//------------------------------------------------------------
BOOL CFinanceApp::InitConfigFile()
{
	CDataFile	IniDF( MONEY_CFG );
	
	if( !IniDF.Load( MONEY_CFG ) ) 
	{
		// create the file
		CDataFile	IniDF;
		CTime		cfgTime_b( 1975, 10, 15, 12, 0, 0 );
		CTime		cfgTime( 2079, 12, 31, 0, 0, 0 );
		time_t		t;
		
		IniDF.CreateSection( "Date range", 
			";[] This section contains date range settings for listview." );
		
		IniDF.SetInt( "range type", 0, "range type is all", "Date range" );
		
		t = cfgTime_b.GetTime();
		IniDF.SetInt( "begindate", t, "", "Date range" );
		
		t = cfgTime.GetTime();
		IniDF.SetInt( "enddate", t,  "", "Date range" );
		

		IniDF.CreateSection( "SQL segment", 
			";[] This section save SQL segment for search" );		
		
		// 0 is FALSE ; 1 is TRUE;
		IniDF.SetInt( "ExactMatch", 0,  "exact or inexact for search", "SQL segment" );
		

		IniDF.CreateSection( "Backup segment", 
			";[] This section record the backup/restore path" );		
		
		IniDF.SetValue( "BakPath", "", "Path for backup", "Backup segment" );

		
		IniDF.SetFileName( MONEY_CFG );
		IniDF.Save();

		
		// <> Run Help when first run
		OnExecHelper();
	}
	
	return TRUE;
}

// 
// 
//------------------------------------------------------------
int CFinanceApp::ExitInstance() 
{
	// Release ADO rec.
	if( m_pConnection != NULL )
	{
		if( m_pConnection->State)
			m_pConnection->Close();
		m_pConnection= NULL;
	}
	
	return CWinApp::ExitInstance();
}

BOOL CAboutDlg::OnInitDialog() 
{
	CDialog::OnInitDialog();
	
	// Set Button 
	m_btnOk.SetIcon(IDI_EYEON, IDI_EYEOFF);
	
	// Set HyperLink for E-Mail
	m_EMailLink.SetURL(IDS_MAILADDR);
	m_EMailLink.SetUnderline(CHyperLink::ulAlways);
	
	// Set HyperLink for Home Page
	m_HomePageLink.SetURL(IDS_WEBADDR);
	m_HomePageLink.SetUnderline(CHyperLink::ulAlways);

	{ // Dynamic popup this dialog !
		ShowWindow(SW_HIDE);
		CRect dlgRect;
		GetClientRect(&dlgRect);
		CPoint centerPoint;
		centerPoint.x=dlgRect.Width()/2;
		centerPoint.y=dlgRect.Height()/2;
		
		CRgn testrgn;
		this->ShowWindow(SW_HIDE);
		
		int m=GetSystemMetrics(SM_CYSIZEFRAME);
		for(int i=10; i < dlgRect.Width()/2+2*m; i+=1)
		{
			testrgn.CreateRectRgn(centerPoint.x-i,centerPoint.y-i,centerPoint.x+i,centerPoint.y+i);
			SetWindowRgn((HRGN) testrgn,TRUE);
			ShowWindow(SW_SHOW);
			CenterWindow();
			testrgn.DeleteObject();
		}
	}	

	UpdateData( FALSE );
	
	return TRUE;  // return TRUE unless you set the focus to a control
	              // EXCEPTION: OCX Property Pages should return FALSE
}


// 
// 
//------------------------------------------------------------
BOOL CFinanceApp::InitRegistry()
{
	HKEY	hRegKey = NULL;

	if( RegOpenKeyEx( HKEY_CURRENT_USER, IDS_REGSRBKEY, 0, KEY_QUERY_VALUE, &hRegKey ) != ERROR_SUCCESS ) 
	{		
		CHAR	chPwd[DEFAULTPWD_LEN] = {0};

		// <> Create SRB soft sub-key 
		if( RegCreateKey( HKEY_CURRENT_USER, IDS_REGSRBKEY, &hRegKey ) != ERROR_SUCCESS )
		{
			::RegCloseKey( hRegKey );
			return FALSE;				
		}
		
		// <> Add the password.
		GetAPDefaultPwd( chPwd );
		if( ::RegSetValueEx( hRegKey, _T("Password"), 0, REG_BINARY, (const unsigned char*)chPwd, strlen(chPwd) ) != ERROR_SUCCESS )
		{
			::RegCloseKey( hRegKey );
			return FALSE;				
		}

		// Enable/Disable Login dlg when start
		BYTE		btPop = 1;
		if( ::RegSetValueEx( hRegKey, _T("Popup"), 0, REG_BINARY, &btPop, sizeof(btPop) ) != ERROR_SUCCESS )
		{
			::RegCloseKey( hRegKey );
			return FALSE;				
		}
	}
	
	::RegCloseKey( hRegKey );
	return TRUE;
}

// 
// 
//------------------------------------------------------------
//DEL void CFinanceApp::AutoBackup()
//DEL {
//DEL 	CShellFileOp	op;
//DEL 	BOOL	bSuccess, bAPICalled = FALSE, bAborted = FALSE;
//DEL 	int		nAPIReturn = 0;
//DEL 	CString strMsg;
//DEL 	
//DEL 
//DEL 	op.SetOperationFlags(  FO_COPY, this,
//DEL                            FOF_FILESONLY | FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION );
//DEL 
//DEL 	op.AddSourceFile( "Mmoney.mdb" );
//DEL 
//DEL 	op.AddDestFile( "Mmoney_bak.mdb" );
//DEL 
//DEL 
//DEL     bSuccess = op.Go( &bAPICalled, &nAPIReturn, &bAborted );
//DEL 
//DEL 
//DEL     strMsg.Format( _T("CShellFileOp::Go() returned %s.\n\nbAPICalled = %s\nnAPIReturn = %d\nbAborted = %s"),
//DEL                     bSuccess ? _T("TRUE") : _T("FALSE"),
//DEL                     bAPICalled ? _T("TRUE") : _T("FALSE"),
//DEL                     nAPIReturn,
//DEL                     bAborted ? _T("TRUE") : _T("FALSE") );
//DEL 
//DEL     AfxMessageBox( strMsg, MB_ICONINFORMATION );
//DEL }
